<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import {useRouter} from "vue-router";
import {ElButton, ElIcon} from "element-plus";
import {Close} from '@element-plus/icons-vue';
const targetId = ref(1);
const comments = ref([]);
const commentContent = ref('');
const replyCommentId = ref(null);
const replyContent = ref('');
const currentParentCommentId = ref(null);
const router = useRouter();

/*const myClick = () => {
  let userId = localStorage.getItem('userId');
  if (!userId) {
    console.log('11111111')
    router.push({ name: 'LoginView' });
    return;
  } else {
    console.log('22222222222222222')
    console.log(userId)
    router.push({ name: 'Comment', query: { id:homepage.value.id } });
  }
};*/

// 删除评论
const deleteComment = async (commentId) => {
  if (!$http || !confirm('确定要删除这条评论吗？')) return;

  try {
    const resp = await $http.delete(`/public/comment/${commentId}`);
    if (resp.data === '删除成功') {
      loadComments(); // 重新加载评论列表
    } else {
      alert('删除失败');
    }
  } catch (err) {
    console.error('删除评论失败：', err);
    alert('删除失败，请重试');
  }
};
const instance = getCurrentInstance();
const $http = instance ? instance.appContext.config.globalProperties.$http : null;

// 加载评论
const loadComments = async () => {
  if (!$http) return;
  try {
    const resp = await $http.get(`/public/comment/query/${targetId.value}`);
    comments.value = resp.data; // 假设后端返回的评论数据在resp.data中
  } catch (err) {
    console.error('加载评论失败：', err);
  }
};

// 发布一级评论
const submitComment = async () => {
  let userId = localStorage.getItem('userId');
  if (!userId) {
    console.log('11111111')
    router.push({ name: 'LoginView' });
    return;
  } else {
    console.log('22222222222222222')
    console.log(userId)
    /*router.push({ name: 'Comment', query: { id:homepage.value.id } });*/
    if (!$http || !commentContent.value) return;
    try {
      await $http.post('/public/comment', {
        content: commentContent.value,
        userId: 1, // 实际应从登录信息获取
        username: '当前用户', // 实际应从登录信息获取
        parentId: 0,
        targetId: targetId.value
      });
      commentContent.value = '';
      loadComments(); // 重新加载评论
    } catch (err) {
      console.error('发布评论失败：', err);
    }
  }
};

// 回复评论 - 新增参数区分是回复一级还是二级评论
const reply = (commentId, isChild = false, parentCommentId = null) => {
  replyCommentId.value = commentId;
  replyContent.value = '';
  // 如果是回复子评论，记录其父评论ID
  if (isChild && parentCommentId) {
    currentParentCommentId.value = parentCommentId;
  } else {
    currentParentCommentId.value = commentId;
  }
};

// 提交回复（子评论）
const submitReply = async () => {
  if (!$http || !replyContent.value || !replyCommentId.value) return;
  try {
    await $http.post('/public/comment', {
      content: replyContent.value,
      userId: 2,
      username: 'ggg',
      parentId: currentParentCommentId.value,
      targetId: targetId.value
    });
    replyCommentId.value = null;
    currentParentCommentId.value = null;
    replyContent.value = '';
    loadComments();
  } catch (err) {
    console.error('提交回复失败：', err);
  }
};


// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleString();
};

onMounted(() => {
  loadComments();
});

const showCommentInput = ref(false);

// 参与讨论按钮点击事件
const handleJoinDiscussion = () => {
  // 切换显示状态（点击显示，再次点击隐藏）
  showCommentInput.value = !showCommentInput.value;
  // 如果显示，则聚焦到输入框
  if (showCommentInput.value) {
    setTimeout(() => { // 延迟一下确保DOM已更新
      const commentInput = document.querySelector('.input-comment textarea');
      if (commentInput) commentInput.focus();
    }, 0);
  }
};

</script>


<template>
  <router-link :to="{name:'qiyu'}">
    <el-affix position="top">
      <el-col  class="text-center">
        <el-icon>
          <ArrowLeft/>
        </el-icon>
      </el-col>
    </el-affix>
  </router-link>
  <div class="action-buttons">
    <el-row gutter="24" class="botton-view">

      <!-- 分享话题按钮 -->
      <el-col :span="8">
        <el-button
            type="text"
            @click="handleShare"
        >
          <el-icon><Share /></el-icon>
          分享话题
        </el-button>
      </el-col>

      <!-- 生成海报按钮 -->
      <el-col :span="8">
        <el-button
            type="text"
            @click="handleGeneratePoster"
        >
          <el-icon><Download /></el-icon>
          生成海报
        </el-button>
      </el-col>


      <el-col :span="8">
        <el-button
            type="primary"
            icon="Edit"
            @click="handleJoinDiscussion"
            class="discussion-btn"
        >
          参与讨论
        </el-button>
      </el-col>
    </el-row>
  </div>
  <div class="comment-container">
    <div v-if="showCommentInput" class="comment-input-container">
      <div style="display: flex; align-items: flex-start; gap: 10px;">
        <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="请输入评论..."
            class="input-comment"
            style="flex: 1;"
        />
        <el-button
            type="text"
            @click="showCommentInput = false"
            style="align-self: flex-start; padding: 5px;"
        >
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <el-button type="primary" @click="submitComment">发布评论</el-button>
    </div>
    <!-- 评论列表 -->
    <div class="comment-list">
      <!-- 即使没有评论也显示提示，而不是完全隐藏 -->
      <div v-if="comments.length === 0" class="no-comment">暂无评论，快来发表第一条评论吧~</div>

      <div v-else v-for="comment in comments" :key="comment.id" class="comment-item">
        <!-- 一级评论 -->
        <div class="parent-comment">
          <div class="user-info">{{ comment.username }} {{ formatTime(comment.createTime) }}</div>
          <div class="content">{{ comment.content }}</div>
          <el-button size="small" @click="reply(comment.id, false)">回复</el-button>
          <!-- 添加删除按钮 -->
          <el-button size="small" type="danger" @click="deleteComment(comment.id)">删除</el-button>
        </div>

        <!-- 子评论列表 -->
        <div class="child-comments">
          <div v-for="child in (comment.children || [])" :key="child.id" class="child-comment">
            <div class="user-info">{{ child.username }} {{ formatTime(child.createTime) }}</div>
            <div class="content">{{ child.content }}</div>
            <el-button size="small" @click="reply(child.id, true, comment.id)">回复</el-button>
            <!-- 添加删除按钮 -->
            <el-button size="small" type="danger" @click="deleteComment(child.id)">删除</el-button>
          </div>
        </div>

        <!-- 回复输入框（点击回复时显示） -->
        <div v-if="replyCommentId === comment.id" class="reply-input">
          <el-input
              v-model="replyContent"
              type="textarea"
              :rows="2"
              placeholder="请输入回复..."
          />
          <el-button size="small" @click="submitReply">发送</el-button>
          <el-button size="small" @click="replyCommentId = null">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
.comment-container {
  padding: 20px;
}
.input-comment {
  margin-bottom: 10px;
}
.comment-list {
  margin-top: 20px;
}
.comment-item {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.parent-comment {
  margin-bottom: 10px;
}
.child-comments {
  margin-left: 20px;
  margin-top: 10px;
}
.child-comment {
  margin-bottom: 10px;
  padding: 5px;
  background: #f5f5f5;
}
.user-info {
  color: #666;
  font-size: 12px;
  margin-bottom: 5px;
}
.content {
  margin-bottom: 5px;
}
.reply-input {
  margin-top: 10px;
  margin-left: 20px;
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  width: 100%;
}

.botton-view {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
}

.text-center {
  font-size: 35px;
  width: 100%;
  cursor: pointer;
}
</style>
